package com.weavernorth.util;

import com.weavernorth.sysap.util.CommonToSapUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import sun.misc.BASE64Encoder;
import weaver.conn.ConnStatement;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

/**
 * @Author: bruseewang
 * @Package: com.weavernorth.util
 * @date: 2020/9/4 16:38
 * @description: 自定义通用工具类
 */
public class MyCommonUtils {
    public static Log log = LogFactory.getLog(MyCommonUtils.class.getName());
    /**
     * 发送post请求,带用户名密码
     *
     * @param strUrl        路径
     * @param strRequestXml 参数(String类型)
     * @param strEncoding   编码格式
     * @param strUsername   用户名
     * @param strPassword   密码
     * @return
     * @throws IOException
     */
    public static String sendPost(String strUrl, String strRequestXml, String strEncoding,String strUsername,String strPassword) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();

        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);
            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //log.info("请求xml=" + strRequestXml);
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
            log.info("请求地址=" + strUrl);

            //sap的接口需验证
            String strValue = "Basic " + (new BASE64Encoder().encode((strUsername + ":" + strPassword).getBytes()));
            httpPost.setHeader("Authorization", strValue);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");

            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                log.info("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }
        return strBody;
    }

    /**
     * 发送post请求（无用户名密码）
     *
     * @param strUrl        路径
     * @param strRequestXml 参数(String类型)
     * @param strEncoding   编码格式
     * @return
     * @throws IOException
     */
    public static String sendPost(String strUrl, String strRequestXml, String strEncoding) throws IOException {
        //基础类
        BaseBean bb = new BaseBean();
        String strBody = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        //创建post方式请求对象
        try {
            HttpPost httpPost = new HttpPost(strUrl);
            //装填参数
            StringEntity stringEntity = new StringEntity(strRequestXml, "utf-8");
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
            log.info("请求地址=" + strUrl);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(httpPost);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                strBody = EntityUtils.toString(entity, strEncoding);
                log.info("返回结果=" + strBody);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
        } catch (Exception e) {
            log.info("异常捕获=" + e);
        }
        return strBody;
    }

    /***
     * 获取xml中返回的状态及信息
     * @param responseXml
     * @return
     */
    public static String[] responseResult(String responseXml){
        String[] strResult=new String[2];
        try {
            Document doc=null;//引用dom4j组件
            doc = DocumentHelper.parseText(responseXml.toString());
            //selectNodes("Type")从当前节点的子节点中选择名为“Type”的节点
            //selectNodes("/Type")从根节点的子节点中选择名为“Type”的节点
            //selectNodes("//Type")从任意节点上选择名为“Type”的节点
            Iterator<Element> its2 = doc.selectNodes("//TYPE").iterator();
            int intType = 0;
            String resultCode=null;//接口返回状态码
            Boolean bolFlag=true;
            String strMessage="";
            while (its2.hasNext()){
                Element element = its2.next();
                resultCode=element.getText();
                if ("E".equals(resultCode)) {
                    bolFlag = false;
                    break;
                }
                intType++;
            }
            int intMess = 0;
            //返回值失败时,则提示失败
            if ("E".equals(resultCode)) {
                Iterator<Element> its3 = doc.selectNodes("//MESSAGE").iterator();
                while (its3.hasNext()) {
                    Element element2 = its3.next();
                    strMessage = element2.getText();
                    if (intMess == intType) {
                        if (!"".equals(strMessage)) {
                            bolFlag = false;
                            break;
                        }
                    }
                    intMess++;
                }
            }
            if (!bolFlag) {
                strResult[0]="f";
                strResult[1]=strMessage;
            } else {
                strResult[0]="s";
                strResult[1]="SUCCESS";
            }
        }catch (Exception e) {
            strResult[0]="e";
            strResult[1]=e.toString();
        }finally {
            return strResult;
        }
    }

    /***
     * 判断某个节点是否存在
     * @param strXml
     * @param strElement
     * @return
     */
    public static Boolean eleisExists(String strXml,String strElement) {
        try {
            Document doc=null;//引用dom4j组件
            doc = DocumentHelper.parseText(strXml.toString());
            Integer count=0;
            count= doc.selectNodes(strElement).size();
            if(count>0){
                return true;
            }
            else{
                return false;
            }
        }catch (Exception e){
            return false;
        }

    }

    /***
     * 根据数据statement和列名,获取列字段类型
     * @param statement
     * @param filedName
     * @return
     */
    public static String getColumnType(ConnStatement statement, String filedName){
        String str=null;
        try{
            int columnCount = statement.getColumnCount();
            for (int i=1;i<=columnCount;i++){
                String columnName= statement.getColumnName(i);
                String columnType=statement.getColumnTypeName(i);
                if (filedName==columnName){
                    str=columnType;
                    break;
                }
            }
        }catch (Exception ex){
            ex.printStackTrace();
            str="1";
        }
        return str;
    }

    /***
     * 根据工号获取人员id
     * @param strWorkcode
     * @return
     */
    public static String getUseridByCode(String strWorkcode) {
        RecordSet rs = new RecordSet();
        //返回人员id
        String strUserid = "";
        rs.executeQuery("select id,departmentId from hrmresource where workcode='"+strWorkcode+"' and (accounttype is null or accounttype=0)");
        if (rs.next()) {
            strUserid = Util.null2String(rs.getString("id"));
        }
        return strUserid;
    }
    /***
     * 根据工号获取人员部门
     * @param strWorkcode
     * @return
     */
    public static String getDepByCode(String strWorkcode) {
        RecordSet rs = new RecordSet();
        //返回人员id
        String strUserid = "";
        rs.executeQuery("select departmentId from hrmresource where workcode='"+strWorkcode+"' and (accounttype is null or accounttype=0)");
        if (rs.next()) {
            strUserid = Util.null2String(rs.getString("departmentId"));
        }
        return strUserid;
    }
}
